package net.sansi.v3correctserver.util;

import cn.hutool.core.thread.ThreadUtil;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Fang
 * create time : 2024/12/17
 * IDE : IntelliJ IDEA
 * <p>
 * windows窗口工具
 */

public class ConfirmUtil extends JDialog {

    private String message = "";

    public ConfirmUtil() {
        this(null, "确认提示", "确认");
    }

    public ConfirmUtil(Frame owner, String title, String message) {
        super(owner, title, false); // 第三个参数为false表示非模态对话框
        this.message = message;
        setLocationRelativeTo(owner);

    }

    public interface With {
        void callback();
    }

    private With with;

    public ConfirmUtil with(With with) {
        this.with = with;
        return this;
    }

    public boolean confirm() {
        setLayout(new BorderLayout());

        JLabel label = new JLabel(message);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        add(label, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton yesButton = new JButton("是");
        JButton noButton = new JButton("否");

        int[] result = {0};

        yesButton.addActionListener(e -> {
            setVisible(false);
            dispose();
            result[0] = 1;
        });

        noButton.addActionListener(e -> {
            setVisible(false);
            dispose();
            result[0] = 2;
        });

        buttonPanel.add(yesButton);
        buttonPanel.add(noButton);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();
        setVisible(true);
        with.callback();
        while (result[0] == 0) {
            ThreadUtil.sleep(100);
        }
        return result[0] == 1;
    }


    /**
     * 确认弹窗
     *
     * @param message 消息
     * @param title   标题
     * @return 是否确认
     */
    public static boolean confirm(String message, String title) {
        return new ConfirmUtil(null, message, title).confirm();
        //int response = JOptionPane.showConfirmDialog(null, message, title,
        //        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        //
        //return response == JOptionPane.YES_OPTION;
    }

    /**
     * 确认弹窗
     *
     * @param message 消息
     * @return 是否确认
     */
    public static boolean confirm(String message) {
        return confirm(message, "确认提示");
    }
}
